<template>
  <van-nav-bar
    title="地址编辑"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
  <van-address-edit
    :area-list="areaList"
    :address-info="addressInfo"
    show-delete
    show-set-default
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    @save="onSave"
    @delete="onDelete"
  />
</template>
<script setup lang="ts">
import { onMounted, ref, reactive } from "vue";
import { showToast } from "vant";
import { areaList } from "@vant/area-data";
import { addressApi } from "@/api/index";
import { useRoute, useRouter } from "vue-router";
import { appStore } from "@/store/appStore";
import { storeToRefs } from "pinia";
let { userId, phone } = storeToRefs(appStore());

const route = useRoute(); //不带r的是获取当前页面url相关参数
const router = useRouter(); //代r的是负责页面跳转
const addressInfo = reactive({
  id: "",
  name: "张飞",
  tel: "13288676",
  province: "",
  city: "",
  county: "",
  areaCode: "",
  addressDetail: "",
  isDefault: false,
});

onMounted(() => {
  if (route.query.id != undefined) {
    addressInfo.id = route.query.id.toString();
  }

  callAddressApi();
});
const callAddressApi = () => {
  addressApi.select.call({ id: addressInfo.id }).then((res: any) => {
    const currAddress = res[0];

    addressInfo.name = currAddress.name;
    addressInfo.tel = currAddress.phone;
    addressInfo.province = currAddress.province;
    addressInfo.city = currAddress.city;
    addressInfo.county = currAddress.country;
    addressInfo.areaCode = currAddress.areaCode;
    addressInfo.addressDetail = currAddress.addressDetail;
    if (currAddress.isDefault === 0) {
      addressInfo.isDefault = true;
    } else {
      addressInfo.isDefault = false;
    }
  });
};

const onDelete = () => {
  addressApi.delete.call({ id: addressInfo.id }).then((res: any) => {
    showToast("删除成功");
    router.push({ name: "address-list" });
  });
};
const onSave = (info: any) => {
  let isDefault = 1;
  if (info.isDefault === true) {
    isDefault = 0;
  }
  const params = {
    id: addressInfo.id,
    name: info.name,
    phone: info.tel,
    province: info.province,
    city: info.city,
    country: info.county,
    areaCode: info.areaCode,
    addressDetail: info.addressDetail,
    isDefault: isDefault,
  };

  addressApi.update.call(params).then((res: any) => {
    showToast("保存成功");
    router.push({ name: "address-list" });
  });
};

const onClickLeft = () => history.back();
</script>
<style scoped>
</style>